package com.zeros.baselibrary.widgets

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.ImageView
import com.zeros.baselibrary.R
import org.jetbrains.anko.dimen

/**
 *   圆角图标
    左上，右上为圆角  ▏2018/5/24.
    wc
 */
class RoundRectImageView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ImageView(context, attrs, defStyleAttr) {

    val radius = dimen(R.dimen.common_radius).toFloat()
    //设置圆角为左上和右上
    private val radiusArray:FloatArray = floatArrayOf(radius,radius,radius,radius,0.0f,0.0f,0.0f,0.0f)


    /*-重新绘制-*/
    override fun draw(canvas: Canvas) {
        var bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        var localCanvas = Canvas(bitmap)
        if (bitmap.isRecycled) {
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            localCanvas = Canvas(bitmap)
        }
        super.draw(canvas)
        drawRoundAngle(localCanvas)
        val paint = Paint()
        paint.xfermode = null
        canvas.drawBitmap(bitmap, 0.0f, 0.0f, paint)
        bitmap.recycle()
    }

    /*-绘制圆角-*/
    private fun drawRoundAngle(canvas: Canvas) {
        val paint = Paint ()
        paint.isAntiAlias = true
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
        val path = Path()
        path.addRoundRect(RectF(0.0f, 0.0f, width.toFloat(), height.toFloat()),
                radiusArray, Path.Direction.CW)//顺时针,CCW逆时针
        path.fillType = Path.FillType.INVERSE_WINDING   //取path所有未占区域；

        canvas.drawPath(path, paint)
    }

}